﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using CharitiesLib;
using Charities.ModelViews;

namespace Charities.Forms
{
    public partial class Shceduals : Form
    {
        Form fo = null;
        int userid;
        public Shceduals(int uid,Form m)
        {
            userid = uid;
            fo = m;
            this.MdiParent = m;
            InitializeComponent();
        }
        ModelContainer ctx = new ModelContainer();
        public bool is_loaded = false;
        private void Shceduals_Load(object sender, EventArgs e)
        {
            is_loaded = true;
            // add this form to window list
            ((Forms.FormMDI)fo).addFormToWindowsList(this);
            User user = ctx.Users.Single(u => u.Id == userid);
            foreach (var Item in user.Role.Permissions)
            {
                switch (Item.Name)
                {
                    case "SHEDUAL_GRANT":
                        btn_deliver.Visible = true;
                        break;
                    case "SHEDUAL_DELETE":
                        btn_Delete.Visible = true;
                        break;
                    
                    default:
                        break;
                }
            }

        }
        
        private void GetSheduals()
        {

            var scheduals = ctx.Schedules.Where(c=>c.NextGrantDate >= dtp_FromDate.Value
                && c.NextGrantDate <= dtp_ToDate.Value)               
                .ToList();
             List<SchedualView> shViewList = new List<SchedualView>();
             foreach (var sch in scheduals)
             {
                 SchedualView shcView = new SchedualView();
                 shcView.WorthyId = sch.Grant.WorthyId;
                 shcView.DateOfGrant = sch.NextGrantDate;
                 shcView.IssuNumber = sch.Grant.IssueNumber;
                 shcView.ShedualType = sch.ScheduleType;
                 shcView.GrantId = sch.GrantId;
                 shcView.Id = sch.Id;
                 Person p = ctx.People.Single(i => i.Id == sch.Grant.Worthy.PersonId);
                 shcView.WorthyName = p.FirstName + " " + p.FatherName + " " + p.LastName;
                 if (sch.InsertDate != null)
                     shcView.insertDate = (DateTime)sch.InsertDate.Value.Date;
                 if (sch.Grant.CartId != null)
                     shcView.GrantSummery += sch.Grant.Cart.Name;
                 else
                 {
                     var gdls = ctx.GrantDetails.Where(c => c.GrantId == sch.GrantId).ToList();
                     foreach (var item in gdls)
                     {
                         shcView.GrantSummery += item.Supply.Name;
                     }
                 }
                 shViewList.Add(shcView);
             }
             dgv_shc_list.DataSource = shViewList;
             dgv_shc_list.Columns["GrantId"].Visible = false;
             dgv_shc_list.Columns["Id"].Visible = false;
         
        }
        private void btn_query_Click(object sender, EventArgs e)
        {
            GetSheduals();
        }

        private void dgv_shc_list_SizeChanged(object sender, EventArgs e)
        {
            for (int i = 0; i < this.dgv_shc_list.ColumnCount; i++)
            {
               
                this.dgv_shc_list.Columns[i].Width = (this.dgv_shc_list.Width - this.dgv_shc_list.RowHeadersWidth) / this.dgv_shc_list.ColumnCount;
            }
        }

        private void Shceduals_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
            // remove this form from windows list
            ((Forms.FormMDI)fo).removeFormFromWindowsList(this);
        }

        private void Shceduals_Activated(object sender, EventArgs e)
        {
            // activate this form and add it windows list as activate one
            ((Forms.FormMDI)this.MdiParent).activateWindow(this);
        }
        bool toggle = false;
        private void dgv_shc_list_ColumnHeaderMouseDoubleClick(object sender, DataGridViewCellMouseEventArgs e)
        {
            foreach (DataGridViewRow row in dgv_shc_list.Rows)
            {
                if (toggle)
                    row.Cells[PickToGrantCheckbox.Name].Value = false;
                else
                    row.Cells[PickToGrantCheckbox.Name].Value = true;
            }

            if (toggle)
                toggle = false;
            else
                toggle = true;
        }

        private void btn_Close_Click(object sender, EventArgs e)
        {
            this.Close();
            is_loaded = false;
        }

        private void btn_Deliver_Click(object sender, EventArgs e)
        {
            List<Worthy> worthies = new List<Worthy>();
            List<Grant> grants = new List<Grant>();

            foreach (DataGridViewRow item in dgv_shc_list.Rows)
            {
                if (item.Cells[0].Value != null)
                {
                    if ((bool)item.Cells[0].Value == true)
                    {
                        if (item.Cells[1].Value.ToString() != String.Empty)
                        {
                            int id = (int)item.Cells[1].Value;
                            Worthy w = ctx.Worthies.Single(c => c.Id == id);
                            DateTime dateOfGrant = (DateTime)item.Cells[4].Value;
                            string issunum = item.Cells[4].Value.ToString();
                            int sgrantId = (int)item.Cells[8].Value;

                            if (ctx.Grants.Where(c => c.Id == sgrantId).Count() == 1)
                            {
                                Grant g = ctx.Grants.Single(c => c.Id == sgrantId);
                                if (w.IsActive)
                                {
                                    worthies.Add(w);
                                    grants.Add(g);
                                }
                                else
                                {
                                    Person p = ctx.People.Single(d => d.Id == w.PersonId);
                                    MessageBox.Show(" لا يمكن إضافة منحة للمستحق: " + p.FirstName + " " + p.LastName + " " + "لكونه مرقن القيد ");
                                }
                            }
                        }
                    }
                }
            }
            if (worthies.Count() > 0 && grants.Count() > 0)
            {
                DialogResult result = MessageBox.Show(" سيتم تسليم " + grants.Count().ToString() + "  منحة هل تريد بالتكيد تسليم المنح وحذفها من الجدولة ؟  ", "تأكيد تسليم المنح", MessageBoxButtons.YesNo);
                if (result == DialogResult.Yes)
                {
                    foreach (var grant in grants)
                    {
                        grant.IsDelivered = true;
                        foreach (var i in grant.GrantDetails.ToList())
                        {
                            if (grant.CartId != null)
                            {
                                List<CartDetail> cdls = ctx.CartDetails.Where(d => d.CartId == grant.CartId).ToList();
                                foreach (var item in cdls)
                                {
                                    Supply supl = ctx.Supplies.Single(cu => cu.Id == item.SupplyId);
                                    supl.Amount = supl.Amount - (i.Amount * item.Amount);
                                }
                            }
                            else
                            {
                                Supply sup = ctx.Supplies.Single(s => s.Id == i.SupplyId);
                                sup.Amount = sup.Amount - i.Amount;
                            }
                        }
                        ctx.Schedules.Remove(ctx.Schedules.Where(c => c.GrantId == grant.Id).FirstOrDefault());
                    }
                    ctx.SaveChanges();
                    GetSheduals();
                }

            }
        }
        
        private void btn_Delete_Click(object sender, EventArgs e)
        {
            DialogResult res = MessageBox.Show("سيتم حذف الجدولة هل أنت متأكد","تأكيد الحذف!",MessageBoxButtons.YesNo,MessageBoxIcon.Warning);
            if (res == DialogResult.Yes)
            {
                List<Grant> grants = new List<Grant>();
                foreach (DataGridViewRow shedual in dgv_shc_list.Rows)
                {
                    if (shedual.Cells[0].Value != null)
                    {
                        if ((bool)shedual.Cells[0].Value == true)
                        {
                            int id;
                            if (int.TryParse(shedual.Cells["Id"].Value.ToString(), out id))
                            {
                                Schedule s = ctx.Schedules.Single(c => c.Id == id);
                                Grant g = ctx.Grants.Single(c => c.Id == s.GrantId);
                                ctx.Grants.Remove(g);
                            }
                        }
                    }
                }
                ctx.SaveChanges();
                GetSheduals();
            }
        }
    }
}
